<template>
	<view class="card-item">
		<text class="label">领料单号：</text>
		<input class="value" v-model="ms.billNo" disabled="false" />
	</view>
	<view class="card-item">
		<text class="label">领料人：</text>
		<input class="value" v-model="workerInput" @blur="getWorker" />
	</view>
	<view class="card-item">
		<text class="label">进仓日期：</text>
		<picker class="value" mode="date" @change="onDateChange" :value="dateValue">
			<view class="date-picker">{{ ms.inOutDate }}</view>
		</picker>
	</view>
	<view class="card-item">
		<text class="label">发料仓库：</text>
		<picker
			class="value"
			:range="options"
			:range-key="'label'"
			@change="handlePickerChange"
		>
			<view class="picker-box">
				{{ selectedLabel || '请选择' }}
			</view>
		</picker>
	</view>
	<view class="card-item">
		<text class="label">领料车间：</text>
		<picker
			class="value"
			:range="options2"
			:range-key="'label'"
			@change="handlePickerChange2"
		>
			<view class="picker-box">
				{{ selectedLabel2 || '请选择' }}
			</view>
		</picker>
	</view>
	<view class="search-bar">
		<button class="scan-btn" @tap="handleScan">扫码</button>
		<input :style="{ 
					opacity: dataScan ? 1 : 0,
					pointerEvents: dataScan ? 'auto' : 'none'
				}" 
		class="search-input" v-model="dataScan" disabled="{{!dataScan}}"/>
		<button class="button-save" @tap="saveDetail">保存</button>
	</view>

	<view>
		<!-- 
		WA_produce_wp_take_return_master
		<text>单号：</text> billNo - 自动获取 搜索查询 1
		<text>送料方式：</text>getMode - 单选 车间自取 仓库送料 0
		<text>备注：</text>remark - text 0
		<text>制单：</text>createBy - 当前用户 1
		<text>送料位置：</text>sendPlace - text -1
		<text>制单日期：</text>createDate - 当前 YYYY-MM-DD hh:mm:ss 1
		<text>领料人：</text>takeReturnPerson 选择 0
		<text>审核：</text>checkBy -1
		<text>单据状态：</text>billStatus - 未审核 1
		<text>领料日期：</text>billStatus - 当前 YYYY-MM-DD 0.5
		<text>需求日期：</text>needDate - 需选择 0
		<text>审核日期：</text>checkDate -1
		<text>备料状态：</text>stockpreparationStatus 未确认
		<text>备料申请：</text>applyBy
		<text>备料确认：</text>confirmBy
		<text>备料开始：</text>startBy
		<text>备料完成：</text>completeBy
		 -->
		<!--
		此处的扫码扫的是车间任务单号 - 明细
		<text>工序：</text>wpCode WA_produce_bill_detail_m
		<text>车间任务单号：</text>productBillNo WA_produce_wp_take_return_detail
		<text>ERP物料编号：</text>standardCode V_goods
		<text>物料编号：</text>goodsCode WA_produce_wp_take_return_detail
		<text>物料名称：</text>goodsName V_goods
		<text>图号-版本/规格：</text>designNumberVerSpec V_goods
		<text>可领料数量：</text>canTakeQty
		WA_produce_bill_detail_m.require_qty - WA_produce_bill_detail_m.already_take_qty + WA_produce_bill_detail_m.already_return_qty as can_take_qty,  
		<text>可申请备料数量：</text>canApplyStockQty
		WA_produce_bill_detail_m.require_qty - WA_produce_bill_detail_m.already_apply_stock_qty + WA_produce_bill_detail_m.already_return_qty as can_apply_stock_qty
		<text>领料数量：</text>qty WA_produce_wp_take_return_detail
		-->
		<view v-for="bd in bv" :key="bd.id" v-if="bv.length > 0">
			<view class="card-pick">
				<view class="card-body">
					<text class="title">工序:</text>
					<input
						v-model="bd.wpName" 
						placeholder="工序名称" 
						disabled="false"
						class="input"
					/>
				</view>
				<view class="card-body">
					<text class="title">车间任务单号:</text>
					<input			
						v-model="bd.productBillNo" 
						placeholder="车间任务单号"
						disabled="false"
						class="input"
					/>
				</view>
				<view class="card-body">
					<text class="title">物料编号：</text>
					<input
						v-model="bd.goodsCode"
						placeholder="物料编号"
						disabled="false"
						class="input"
					/>
				</view>
				<view class="card-body">
					<text class="title">物料名称：</text>
					<input
						v-model="bd.goodsName"
						placeholder="物料名称"
						disabled="false"
						class="input"
					/>
				</view>
				<view class="card-body">
					<text class="title">可申请备料数量：</text>
					<input
						v-model="bd.canApplyStockQty"
						placeholder="可申请备料数量"
						disabled="false"
						class="input"
					/>
				</view>
				<view class="card-body">
					<text class="title">可领料数量：</text>
					<input
						v-model="bd.canTakeQty"
						placeholder="可领料数量"
						disabled="false"
						class="input"
					/>
				</view>
				<view class="card-body">
					<text class="title">领料数量：</text>
					<input
						v-model="bd.qty"
						placeholder="领料数量" 
						class="input"
					/>
				</view>
				<view v-for="w in wa">
					<text>库位：</text>
					<text>{{w.workingAreaName}} - {{w.worikingCenterCode}} - {{w.waLocationName}}</text>
					<text> 现存量：</text>
					<text>{{w.onHandQty}}</text>
				</view>
			</view>
		</view>
		<!-- 
		库位
		<text>物料编号：</text>goodsCode
		<text>仓库：</text>workingAreaCode
		<text>库位：</text>locationCode
		<text>库位现存量：</text>onHandQty
		 -->
	</view>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { LAN_URL } from '@/pages/config/global'

const USER_OPRIONS_URL = '/produceRepair/userOptions'
const PICK_DETAIL_URL = '/pick/getDetail'
const SAVE_URL = '/pick/save'
const GETNUM_URL = '/produceDetail/getBillNum'
	const GET_WORKER_URL = '/pick/getWorker'
	const GET_WPNAME_RUL = '/productBillDetail/getWpCn'

const billDetailData = ref(false);
const workingAreaCode = ref(null);
const takeReturnWorkingAreaCode = ref(null);
const dataScan = ref('');
const scanModalData = ref<any>([]);
const userID = ref<string | null>(null);
const userName = ref<string | null>(null);
const workerInput = ref('');
const workerCode = ref('');
const moduleID = '工序领料单录入';

const options = ref<OptionItem[]>([]);
const selectedValue = ref('');
const selectedLabel = ref('');
const options2 = ref<OptionItem[]>([]);
const selectedValue2 = ref('');
const selectedLabel2 = ref('');
const stockpreparationStatus = ref('');

const dateValue = ref<string>(formatTimePicker(new Date()))

interface OptionItem {
	label: string;
	value: string;
}

const bv = ref<billView[]>([]);
interface billView {
	id: number,
	wpCode: string,
	wpName: string,
	productBillNo: string,
	standardCode: string,
	goodsCode: string,
	goodsName: string,
	designNumberVerSpec: string,
	canTakeQty: number,
	canApplyStockQty: number,
	qty: number,
}

const wa = ref<waLocation[]>([])
interface waLocation {
	workingAreaCode: string,
	worikingCenterCode: string,
	waLocationName: string,
	workingAreaName: string,
	onHandQty: number,
}

const ms = ref<Master | null>({
	billNo: '',
	billStatus: '',
	billType: '',
	inOutDate: '',
	createBy: '',
	createDate: '',
});
interface Master {
	billNo: string,
	billStatus: string,
	billType: string,
	inOutDate: string,
	createBy: string,
	createDate: string,
}

onMounted(() => {
	loadUserInfo();
	fetchOptions();
	
	ms.value.inOutDate = getTime();
	ms.value.billStatus = '未审核';
	ms.value.billType = '工序领料单';
})

/* 加载用户信息 */
const loadUserInfo = () => {
	const user = uni.getStorageSync('user');
	if (user) {
		userID.value = user.id;
		userName.value = user.name;
	}
};

/* 获取仓库选项 */
const fetchOptions = async () => {
	try {
		const user = uni.getStorageSync('user')
		const userID = ref<string | null>(null)
		userID.value = user.id
		const res = await uni.request({
			url: `${LAN_URL}${USER_OPRIONS_URL}`,
			method: 'POST',
			header: {
				'Content-Type': 'application/json',			
			},
			data: {
				property: "仓库",
				userID: userID.value
			}
		})
		if (res.statusCode === 200) {
		    const data = res.data as any[]
		    options.value = data.map(item => ({
		        label: item.label,
		        value: item.value
		    }))
		} else {
		    console.error('发料仓库数据请求失败', res)
		}
		const res2 = await uni.request({
			url: `${LAN_URL}${USER_OPRIONS_URL}`,
			method: 'POST',
			header: {
				'Content-Type': 'application/json',			
			},
			data: {
				property: "%车间",
				userID: userID.value
			}
		})
		if (res2.statusCode === 200) {
		    const data = res2.data as any[]
		    options2.value = data.map(item => ({
		        label: item.label,
		        value: item.value
		    }))
		} else {
		    console.error('领料车间数据请求失败', res2)
		}
	}catch {
		uni.showToast({ title: '获取数据失败', icon: 'none' })
	}
}

/* 扫码 */
const handleScan = async () => {
	if(workingAreaCode.value == null) {
		uni.showToast({
			title: '请选择发料仓库',
			icon: 'none'
		})
		return;
	}
	if(takeReturnWorkingAreaCode.value == null) {
		uni.showToast({
			title: '请选择领料车间',
			icon: 'none'
		})
		return;
	}
	try {
		const res = uni.scanCode({
			scanType: ['qrCode', 'barCode'],
			onlyFromCamera: true,
			success: (result) => {
				handleScanResult(result)
			},
			fail: (err) => {
				handleScanError(err)
			}
		})
	} catch (error) {
		handleScanError(error)
	}
}
/* 扫码结果处理 */
const handleScanResult = (result: UniApp.ScanCodeSuccessRes) => {
	dataScan.value = result.result.trim()
	if (result.scanType === 'EAN_13') {
		console.log("1")
	}
	fetchDetailData()
}
/* 扫码错误 */
const handleScanError = (error: any) => {
	console.error('扫码失败:', error)
	uni.showToast({
		title: '扫码失败，请重试',
		icon: 'none'
  })
}

/* 获取明细数据 */
const fetchDetailData = () => {
	try {
		uni.request({
			url: `${LAN_URL}${PICK_DETAIL_URL}`,
			method: 'POST',
			data: { billNo: dataScan.value },
			success: (res) => {
				if(res.statusCode == 200 && res.data.length > 0){
					if (Array.isArray(res.data)) {
						res.data.forEach((item: any) => {
							const billViewItem: billView = {
							    id: item.id || 0,
							    wpCode: item.wpCode || '',
								wpName: item.wpName || '',
							    productBillNo: item.productBillNo || '',
							    standardCode: item.standardCode || ' ',
							    goodsCode: item.goodsCode || '',
							    goodsName: item.goodsName || '',
							    designNumberVerSpec: item.designNumberVerSpec || '',
							    canTakeQty: item.canTakeQty || 0,
							    canApplyStockQty: item.canApplyStockQty || 0,
							    qty: item.qty || 0,
							};
							const LocationItem: waLocation = {
								workingAreaCode: item.workingAreaCode || '',
								worikingCenterCode: item.worikingCenterCode || '',
								waLocationName: item.waLocationName || '',
								workingAreaName: item.workingAreaCode || '',
								onHandQty: item.workingAreaCode || 0,
							}
							bv.value.push(billViewItem);
							wa.value.push(LocationItem);
						})
					}else {
						scanModalData.value = res.data[0] || res.data
						const billViewItem: billView = {
						    id: scanModalData.value.id || 0,
						    wpCode: scanModalData.value.wpCode || '',
							wpName: scanModalData.value.wpName || '',
						    productBillNo: scanModalData.value.productBillNo || '',
						    standardCode: scanModalData.value.standardCode || '',
						    goodsCode: scanModalData.value.goodsCode || '',
						    goodsName: scanModalData.value.goodsName || '',
						    designNumberVerSpec: scanModalData.value.designNumberVerSpec || '',
						    canTakeQty: scanModalData.value.canTakeQty || 0,
						    canApplyStockQty: scanModalData.value.canApplyStockQty || 0,
						    qty: scanModalData.value.qty || 0,
						};
						const LocationItem: waLocation = {
							workingAreaCode: scanModalData.value.workingAreaCode || '',
							worikingCenterCode: scanModalData.value.worikingCenterCode || '',
							waLocationName: scanModalData.value.waLocationName || '',
							workingAreaName: scanModalData.value.workingAreaCode || '',
							onHandQty: scanModalData.value.workingAreaCode || 0,
						}
						bv.value.push(billViewItem);
						wa.value.push(LocationItem);
					}
				}else {
					uni.showToast({
						title: '数据异常',
						icon: 'none'
					})
				}
			},
			fail() {
				uni.showToast({
					title: '网络异常',
					icon: 'none'
				})
			}
		})
		billDetailData.value = true
	}catch {
		uni.showToast({
			title: '网络异常',
			icon: 'none'
		})
	}
}

/* 变更发料仓库 */
const handlePickerChange = (e: any) => {
	const index = e.detail.value
	selectedValue.value = options.value[index].value
	selectedLabel.value = options.value[index].label
	workingAreaCode.value = selectedValue.value
}
/* 变更领料车间 */
const handlePickerChange2 = (e: any) => {
	const index = e.detail.value
	selectedValue2.value = options2.value[index].value
	selectedLabel2.value = options2.value[index].label
	takeReturnWorkingAreaCode.value = selectedValue2.value
}

/* 保存 */
const saveDetail = () => {
	const chineseRegex = /[\u4e00-\u9fa5]/;
	if(!chineseRegex.test(workerInput.value)){
		uni.showToast({
			title: '请获取正确的领料人',
			icon: 'none'
		})
		return;
	}
	if(workingAreaCode.value == null) {
		uni.showToast({
			title: '请选择发料仓库',
			icon: 'none'
		})
		return;
	}
	if(takeReturnWorkingAreaCode.value == null) {
		uni.showToast({
			title: '请选择领料车间',
			icon: 'none'
		})
		return;
	}
	if(!(bv.value && bv.value.length > 0)) {
		uni.showToast({
			title: '请获取明细',
			icon: 'none'
		})
		return;
	}
	if(ms.value.billNo.trim() == '' || ms.value.billNo == null){
		getBillNo();
	}else {
		handleSave();
	}
}

/* 当单号为空时获取单号 */
const getBillNo = () => {
	if(ms.value.billNo == ''){
		uni.request({
			url: `${LAN_URL}${GETNUM_URL}`,
			method: 'POST',
			data: {
				billName: ms.value.billType
			},
			success: (res) => {
				if (res.data && res.data != null && res.data != "取单号时出错") {
					ms.value.billNo = res.data;
					handleSave();
				} else {
					uni.showToast({
						title: '保存失败，请重新保存',
						icon: 'none'
					});
					return;
				}
			}, fail() {
				uni.showToast({
					title: '保存失败，请重新保存',
					icon: 'none'
				});
				return;
			}
		})
	}else {
		//updateDetail();
	}
}
const handleSave = () => {
	ms.value.createDate	= getTime();
	ms.value.createBy = userName.value
	uni.request({
		url: `${LAN_URL}${SAVE_URL}`,
		method: 'POST',
		data: {
			master: ms.value,
			workingAreaCode: workingAreaCode.value,
			takeReturnWorkingAreaCode: takeReturnWorkingAreaCode.value,
			stockpreparationStatus: stockpreparationStatus.value,
			detail: bv.value,
			takeReturnPerson: workerInput.value,
			WrokerCode: workerCode.value
		},success(res) {
			if(res.data != null && res.statusCode == 200) {
				if(res.data == '1'){
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})
				}else if(res.data == '0') {
					uni.showToast({
						title: '数据异常请检查',
						icon: 'none'
					})
				}
			}
		},fail() {
			uni.showToast({
				title: '网络错误',
				icon: 'none'
			})
		}
	})
}

const getWorker = () => {
	workerCode.value = workerInput.value
	uni.request({
		url: `${LAN_URL}${GET_WORKER_URL}`,
		method: 'POST',
		data: {
			workerCode: workerInput.value
		},
		success(res) {
			if(res.data && res.data != null){
				workerInput.value = res.data;
			}
		},fail() {
			uni.showToast({
				title: '网络异常',
				icon: 'none'
			})
		}
	})
}

const formattedDate = computed(() => {
	const date = new Date(dateValue.value)
	return formatDisplay(date)
})
const onDateChange = (e: any) => {
    ms.value.inOutDate = e.detail.value;
	console.log(ms.value.inOutDate)
}

const getTime = () => {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	const day = String(now.getDate()).padStart(2, '0');
	const hours = String(now.getHours()).padStart(2, '0');
	const minutes = String(now.getMinutes()).padStart(2, '0');
	const seconds = String(now.getSeconds()).padStart(2, '0');
	
	const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	return formattedDate;
}

function formatTimePicker(date: Date): string {
	const pad = (n: number) => n.toString().padStart(2, '0')
	const year = date.getFullYear()
	const month = pad(date.getMonth() + 1)
	const day = pad(date.getDate())
	return `${year}-${month}-${day}`
}
function formatDisplay(date: Date): string {
	const pad = (n: number) => n.toString().padStart(2, '0')	
	return `${date.getFullYear()}年${pad(date.getMonth() + 1)}月${pad(date.getDate())}日`
}

</script>

<style>
	.card-pick {
		margin: 10px;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		background-color: #fff;
		overflow: hidden;
	}
	.card-body {
		margin-bottom: 5rpx;
		display: flex;
		align-items: center;
	}
	.search-bar {
		display: flex;
			align-items: center;
			margin-bottom: 30rpx;
			gap: 20rpx;
	}
	.scan-btn {
		flex-shrink: 0;
		margin-left: 10rpx;
	}
	.search-input {
		flex: 1;
		height: 80rpx;
		padding: 0 30rpx;
		border: 1rpx solid #ddd;
		color: #888;
		border-radius: 40rpx;
	}
	.card-item {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 16rpx;
	}
	.label {
		width: 200rpx;
		color: #888;
		font-weight: bold;
	}
	.value {
		flex: 1;
		color: #333;
		border: 1px solid #ccc;
		border-radius: 8rpx;
	    padding: 8rpx;
	    background-color: #f9f9f9;
	}
	.waDataWindow {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}
	.title {
		font-size: 32rpx;
		font-weight: bold;
		width: 50%;
		display: inline-block;
		margin-bottom: 10rpx;
		margin-left: 5rpx;
	}
	.input {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		padding: 0 20rpx;
		margin-bottom: 10rpx;
	}
	.button-save{
		margin-right: 10rpx;
		background: #007aff;
		color: white;
	}
</style>
